Primary exercises
- A function with
if/elsestatements.
Let’s take the following from a World Health Organization document:
- An
adultis a person older than 19 years of age unless national law defines a person as being an adult at an earlier age. - An
adolescentis a person aged 10 to 19 years inclusive. - A
childis a person 19 years or younger unless national law defines a person to be an adult at an earlier age. - However, in these guidelines when a person falls into the 10 to 19 age category they are referred to as an adolescent (see adolescent definition).
- An
infantis a child younger than one year of age.
The categories can be enumerated as follows:
| group | condition for age [y] |
|---|---|
adult |
age > 19 |
adolescent |
age >= 10 && age <= 19 |
child |
age >= 1 && age < 10 |
infant |
age < 1 |
Implement a function ageGroup which takes age argument (in years) and returns the age group label.
Function template Here is a template of the ageGroup function:
ageGroup <- function( age ) {
# age: age given in years
...
}
and here are expected results:
ageGroup(0) # "infant"
ageGroup(10) # "adolescent"
ageGroup(9) # "child"
ageGroup(20) # "adult"
ageGroup(-1) # should generate an error
To generate the error we request the program to ?stop with an error message.
# 1) Poor implementation
#
ageGroup <- function( age ) {
# age: age given in years
result <- "child"
if( age > 19 ) {
result <- "adult"
}
if( age >= 10 & age <= 19 ) {
result <- "adolescent"
}
if( age < 1 ) {
result <- "infant"
}
if( age < 0 ) {
stop( "Age can't be negative." )
}
result
}
# 2) Improved implementation
#
# In the previous scenario: when `age` is 30 and the `result` is set to `adult`
# it makes no sense to check whether `age` is in other ranges,
# `if`/`else` construction allows for that.
#
ageGroup <- function( age ) {
# age: age given in years
if( age > 19 ) {
result <- "adult"
} else if( age >= 10 ) {
result <- "adolescent"
} else if( age >= 1 ) {
result <- "child"
} else if( age >= 0 ) {
result <- "infant"
} else {
stop( "Age can't be negative." )
}
result
}
ageGroup(0) # "infant"
[1] "infant"
ageGroup(10) # "adolescent"
[1] "adolescent"
ageGroup(9) # "child"
[1] "child"
ageGroup(20) # "adult"
[1] "adult"
ageGroup(-1) # should generate an error
Error in ageGroup(-1): Age can't be negative.